﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using Utility;

namespace BusinessLogic
{
    public class CacheQueryData
    {
        const string CONST_CACHE_TIME_MARK = "CUSTOM_CACHE_TIME_MARK";
        const string CONST_CACHE_TIMEOUT = "CACHE_TIMEOUT";

        public static object GetCache(Dictionary<string, object> pass_params)
        {
            if (!pass_params.ContainsKey("cache_code"))
            {
                return null;
            }

            HttpContext context = HttpContext.Current;
            Cache cache = context.Cache;
            if (cache[CONST_CACHE_TIME_MARK] == null)
            {
                return null;
            }

            try
            {
                string cache_timeout = System.Configuration.ConfigurationManager.AppSettings[CONST_CACHE_TIMEOUT];
                if (!string.IsNullOrEmpty(cache_timeout))
                {
                    DateTime _cacheTime = DateTime.MinValue;
                    if (DateTime.TryParse(cache_timeout, out _cacheTime))
                    {
                        DateTime time_mark = (DateTime)cache[CONST_CACHE_TIME_MARK];
                        if (_cacheTime > time_mark)
                        {
                            Logger.Instance.WriteEventLog("使用缓存", string.Format("开始清理过去缓存,缓存注入时间:{0:yyMd hh:mm}  失效时间:{1:yyMd hh:mm}", time_mark, _cacheTime), LoggerSubDir.cache);
                            List<string> cacheList = new List<string>();
                            System.Collections.IDictionaryEnumerator enumerator = cache.GetEnumerator();
                            if (enumerator != null)
                            {
                                while (enumerator.MoveNext())
                                {
                                    if (enumerator.Key.ToString().StartsWith("CUSTOM_"))
                                    {
                                        cacheList.Add(enumerator.Key.ToString());
                                    }
                                }
                            }
                            foreach (string cacheName in cacheList)
                            {
                                cache.Remove(cacheName);
                            }
                        }
                    }
                }
                Dictionary<string, object> dic = JSONHelper.Instance.JavaScriptDeserializationMachion<Dictionary<string, object>>(pass_params["cache_code"].ToString());
                string keyword = "CUSTOM_SP_" + GetCacheKeywords(dic);
                if (cache[keyword] != null)
                {
                    Logger.Instance.WriteEventLog("使用缓存", keyword+ "读取緩存成功", LoggerSubDir.cache);
                    return cache[keyword];
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteEventLog("使用缓存","读入緩存失败",pass_params, ex, LoggerSubDir.cache);
            }
            return null;
        }

        static string GetCacheKeywords(Dictionary<string, object> dic)
        {
            if (dic.Keys.Count == 0)
            {
                throw new NullReferenceException("生成缓存key失败，参数无值");
            }
            List<string> lstKeys = new List<string>();

            foreach (string key in dic.Keys)
            {
                lstKeys.Add(key);
            }
            lstKeys.Sort();
            string sp_name = "";
            foreach (string key in lstKeys)
            {
                sp_name += dic[key].ToString() + "_";
            }
            return sp_name;
        }

        public static void SetCache(Dictionary<string, object> pass_params, object data)
        {
            if (!pass_params.ContainsKey("cache_code"))
            {
                return;
            }
            try
            {
                Dictionary<string, object> dic = JSONHelper.Instance.JavaScriptDeserializationMachion<Dictionary<string, object>>(pass_params["cache_code"].ToString());
                HttpContext context = HttpContext.Current;
                Cache cache = context.Cache;
                string keyword = "CUSTOM_SP_" + GetCacheKeywords(dic);

                if (cache[CONST_CACHE_TIME_MARK] == null)
                {
                    string cache_timeout = System.Configuration.ConfigurationManager.AppSettings[CONST_CACHE_TIMEOUT];
                    DateTime _cacheTime = DateTime.Now;
                    if (!DateTime.TryParse(cache_timeout, out _cacheTime))
                    {
                        _cacheTime = DateTime.Now;
                    }
                    cache.Insert(CONST_CACHE_TIME_MARK, _cacheTime, null, DateTime.Now.AddMonths(1), Cache.NoSlidingExpiration);
                    Logger.Instance.WriteEventLog("使用缓存",string.Format("{1}注入緩存验证时间戳，有效值1个月,时间戳:{0:yyMd hh:mm}", _cacheTime,CONST_CACHE_TIME_MARK),LoggerSubDir.cache);
                }

                if (cache[keyword] != null)
                {
                    cache[keyword] = data;
                }
                else
                {
                    cache.Insert(keyword, data, null, DateTime.Now.AddDays(15), Cache.NoSlidingExpiration);
                }
                Logger.Instance.WriteEventLog("使用缓存", keyword+ "注入緩存，有效值15天", LoggerSubDir.cache);
            }
            catch(Exception ex) {
                Logger.Instance.WriteEventLog("使用缓存","注入緩存失败", pass_params,ex, LoggerSubDir.cache);
                return;
            }
        }

    }
}
